package cn.wen.service.impl;

import cn.wen.dao.SolutionDao;
import cn.wen.dto.DiscussParam;
import cn.wen.dto.SolutionParam;
import cn.wen.entity.Solution;
import cn.wen.mapper.SolutionMapper;
import cn.wen.service.SolutionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FY
 * @since 2022-02-13
 */
@Service
public class SolutionServiceImpl extends ServiceImpl<SolutionMapper, Solution> implements SolutionService {

    @Resource
    private SolutionMapper solutionMapper;

    @Resource
    private SolutionDao solutionDao;

    @Override
    public Map<String, Object> list(String keyword, Integer pageSize, Integer pageNum, Long subjectId) {
        List<SolutionParam> list = solutionDao.solutionList(keyword,subjectId);
        PageInfo pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",pageInfo.getTotal());
        return map;
    }

    @Override
    public boolean updateSolution(Solution solution) {
        return solutionDao.updateSolution(solution);
    }

    @Override
    public boolean createSolution(SolutionParam solutionParam, Long userId) {
        Solution solution = new Solution();
        BeanUtils.copyProperties(solutionParam,solution);
        if (solution.getSolutionStatus() == 1){
            boolean b = solutionDao.updateStatusIfAll(solutionParam.getSubjectId(),0);
        }
        solution.setUpdateTime(new Date());
        solution.setCreateTime(new Date());
        int insert = solutionMapper.insert(solution);
        if (insert <0){
            return false;
        }
        boolean result = solutionDao.insertUserSolutionSubjectRelation(userId, solution.getId(), solutionParam.getSubjectId());
        return result;
    }

    @Override
    public boolean delete(Long id) {
        int i = solutionMapper.deleteById(id);
        if ( i<0 ) return false;
        return solutionDao.deleteUserSolutionSubjectRelation(id);
    }

    @Override
    public boolean updateStatus(Long solutionId, Long subjectId, Integer status) {
        /**
         * 先找到所以 subject的数据再修改
         */
        if (status == 1){
            boolean b = solutionDao.updateStatusIfAll(subjectId,0);
        }
        Solution solution = new Solution();
        solution.setSolutionStatus(status);
        solution.setId(solutionId);
        return updateSolution(solution);
    }
}
